package com.prestamomo.vil.ppa.pmvilpage;

import static com.prestamomo.vil.ppa.pmvilpage.PmvilPlaceVy.bitmapPmvilToBase64;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.prestamomo.vil.ppa.R;
import com.prestamomo.vil.ppa.pmvilapi.PmSdoxixEtty;
import com.prestamomo.vil.ppa.pmvilapi.PmSkZnh;
import com.prestamomo.vil.ppa.pmvilapi.PmvilHttpRequest;
import com.prestamomo.vil.ppa.pmvilapi.PmvilStillResult;
import com.prestamomo.vil.ppa.pmvilnet.pmvillistener.PmvilCallBack;
import com.prestamomo.vil.ppa.pmvilpage.pmfitter.PmvilXIanFitter;
import com.prestamomo.vil.ppa.pmvilpage.pmrot.PmvilAtyRoot;

import org.jetbrains.annotations.Nullable;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * 创建日期：2023/12/1
 * 文件名称：PmvilXianhuk
 * 文件描述：
 */
public class PmvilXianhuk extends PmvilAtyRoot {

    private String mPmhkje;
    private String qudstr;
    private int mType;
    private int mRepayid;
    private TextView mTj;
    private RecyclerView mImges;
    private TextView mYhzh;
    private TextView mBankname;
    private TextView mHkje;
    private ImageView mBanckse;

    private List<Uri> imgList = new ArrayList<>();
    List<Bitmap> images = new ArrayList<>();
    private Uri mUri = null;
    private PmvilXIanFitter mPmvilXIanFitter;

    @Override
    protected int getPmvilLayoutId() {
        return R.layout.pml_xijah_vy;
    }

    @Override
    protected void showPmvilUi() {
        mBanckse = findViewById(R.id.xis_pmvil_iv_back);
        mHkje = findViewById(R.id.hkje);
        mBankname = findViewById(R.id.bankname);
        mYhzh = findViewById(R.id.yhzh);
        mImges = findViewById(R.id.imges);
        mTj = findViewById(R.id.tj);
        mPmhkje = getIntent().getStringExtra("pmhkje");
        qudstr = getIntent().getStringExtra("qudstr");
        mType = getIntent().getIntExtra("type", 0);
        mRepayid = getIntent().getIntExtra("repayid", 0);
        mHkje.setText(mPmhkje);

        imgList.add(mUri);
        mPmvilXIanFitter = new PmvilXIanFitter(this, imgList);
        mImges.setAdapter(mPmvilXIanFitter);
        ActivityResultLauncher ChooseImg = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if(result.getResultCode() == RESULT_OK)
                        {
                            if(result.getData() != null)
                            {
                                String im = result.getData().toString();
                                //result是ActivityResult类型，result.getData()是intent类型，result.getData().getData()是Uri类型
                                Uri imuri = result.getData().getData();
                                //得到的是：Intent { dat=content://com.android.providers.media.documents/document/image:197731 flg=0x1 }
                                //Bitmap bim = B
//                                ivChoose.setImageURI(imuri);
                                showPmvilLoading();
                                try {
                                    InputStream inputStream = getContentResolver().openInputStream(imuri);
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    //设置为将图片压缩为原来的三分之一大小
                                    options.inSampleSize = 3;
                                    Bitmap bm = BitmapFactory.decodeStream(inputStream, null, options);
                                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                    //再次将bitmap压缩
                                    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                                    int qua = 100;
                                    //查看大小是否大于200kb,大于则再次进行压缩
                                    while (baos.toByteArray().length /1024 >200){
                                        baos.reset();
                                        bm.compress(Bitmap.CompressFormat.JPEG, qua, baos);
                                        //每次减少5%质量
                                        if (qua>5){
                                            qua -=5;
                                        } else {
                                            break;
                                        }
                                    }
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            hindPmvilLoading();
                                            images.add(0,bm);
                                            if (imgList.size() == 3) {
                                                imgList.remove(2);
                                            }
                                            imgList.add(0, imuri);
                                            mPmvilXIanFitter.setDate(imgList);
                                        }
                                    });
                                } catch (FileNotFoundException e) {
                                    throw new RuntimeException(e);
                                }

                            }
                        }
                    }
                }
        );
        mPmvilXIanFitter.setPmlIseItmCliw(new PmvilXIanFitter.PmlIseItmCliw() {
            @Override
            public void pailwei() {
                Intent Album = new Intent(Intent.ACTION_GET_CONTENT);
                //ACTION_GET_CONTENT是获取本地所有图片，ACTION_PICK获取的是相册中的图片
                Album.setType("image/*");
                //设置图像类型
                ChooseImg.launch(Album);
            }

            @Override
            public void delectImt(int postion) {

                if (imgList.size() == 3) {
                    if (imgList.get(2)!=null) {
                        imgList.remove(postion);
                        images.remove(postion);
                        imgList.add(mUri);
                    } else {
                        imgList.remove(postion);
                        images.remove(postion);
                    }
                } else {
                    imgList.remove(postion);
                    images.remove(postion);
                }
                mPmvilXIanFitter.setDate(imgList);
            }
        });
    }


    @Override
    protected void clickePmvil() {
        mBanckse.setOnClickListener(view -> finish());
        mTj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (imgList.size() == 1) {
                    tostPmvilErrMsg("未選擇圖片");
                    return;
                }
                List<String> base64Lis = new ArrayList<>();
                for (int i = 0; i < images.size(); i++) {
                    if (images.get(i)!=null) {
                        String facePmvilStr = bitmapPmvilToBase64(images.get(i));
                        if (!facePmvilStr.startsWith("data:image/jpeg;base64,")) {
                            facePmvilStr = "data:image/jpeg;base64," + facePmvilStr;
                        }
                        base64Lis.add(facePmvilStr);
                    } else {
                        break;
                    }
                }

                if (mType == 0) {
                    manual(base64Lis);
                }else{
                    comitLeftOverPmvilInfoses(base64Lis);
                }

            }
        });
    }


    @Override
    protected void loadPmvilData() {
        collect();
    }

    private void comitLeftOverPmvilInfoses(List<String> imglse) {
        showPmvilLoading();
        PmvilHttpRequest.comitLeftOverPmvilInfoses(this, imglse, mRepayid,qudstr, new PmvilCallBack<PmvilStillResult>() {
            @Override
            public void onPmvilSucc(String pmvilMethod, PmvilStillResult pmvilContent) {
                hindPmvilLoading();
                if(pmvilContent.getPmvilstatus().equals("S")){
                    tostPmvilErrMsg(pmvilContent.getPmvilresMsg());
                    finish();
                }else{
                    tostPmvilErrMsg(pmvilContent.getPmvilresMsg());
                }
            }

            @Override
            public void onPmvilLogOn(String pmvilMod, PmvilStillResult pmvilCtent) {
                outpmvilLongin();
            }

            @Override
            public void onPmvilOther(String pmvilMhod, PmvilStillResult pmvilCnt, String pmvilCode, String pmvilMsg) {
                tostPmvilErrMsg(pmvilMsg);
            }

            @Override
            public void onPmvilFailure(String pmvilMod, String pmvilError) {
                tostPmvilErrMsg(pmvilError);
            }
        });
    }

    private void manual(List<String> imglse) {
        showPmvilLoading();
        PmvilHttpRequest.manual(this, imglse, mRepayid, new PmvilCallBack<PmSdoxixEtty>() {
            @Override
            public void onPmvilSucc(String pmvilMethod, PmSdoxixEtty pmvilContent) {
                hindPmvilLoading();
                if (pmvilContent.getStatus().equals("S")) {
                    tostPmvilErrMsg(pmvilContent.getResMsg());
                    finish();
                } else {
                    tostPmvilErrMsg(pmvilContent.getResMsg());
                }
            }

            @Override
            public void onPmvilLogOn(String pmvilMod, PmSdoxixEtty pmvilCtent) {
                outpmvilLongin();
            }

            @Override
            public void onPmvilOther(String pmvilMhod, PmSdoxixEtty pmvilCnt, String pmvilCode, String pmvilMsg) {
                tostPmvilErrMsg(pmvilMsg);
            }

            @Override
            public void onPmvilFailure(String pmvilMod, String pmvilError) {
                tostPmvilErrMsg(pmvilError);
            }
        });
    }

    private void collect() {
        showPmvilLoading();
        PmvilHttpRequest.collect(this, mRepayid, new PmvilCallBack<PmSkZnh>() {
            @Override
            public void onPmvilSucc(String pmvilMethod, PmSkZnh pmvilContent) {
                hindPmvilLoading();
                mBankname.setText(pmvilContent.getBankName());
                mYhzh.setText(pmvilContent.getBankNum());
            }

            @Override
            public void onPmvilLogOn(String pmvilMod, PmSkZnh pmvilCtent) {
                outpmvilLongin();
            }

            @Override
            public void onPmvilOther(String pmvilMhod, PmSkZnh pmvilCnt, String pmvilCode, String pmvilMsg) {
                tostPmvilErrMsg(pmvilMsg);
            }

            @Override
            public void onPmvilFailure(String pmvilMod, String pmvilError) {
                tostPmvilErrMsg(pmvilError);
            }
        });
    }
}

